package com.poi.exp.writer;

import java.util.HashMap;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.poi.common.CoreConstants;
import com.poi.exp.domain.BaseModel;
import com.poi.exp.domain.CellModelVO;
import com.poi.exp.domain.LoopRowModelVO;
import com.poi.exp.domain.RowModelVO;
import com.poi.util.ExcelOneSheetUtil;
import com.poi.util.ExcelOperationUtil;
import com.poi.util.PoiContextUtil;
import com.poi.util.RegexUtils;

/**
 * <poi:foreach></poi:foreach>的处理器
 * 
 * @author wzy
 *
 */
public class LoopRowWriter implements RowWriter {
	private static final Logger log = LoggerFactory.getLogger(LoopRowWriter.class);

	public void writerRow(RowModelVO rowModelVO, Sheet sheet) {
		writerRow(rowModelVO,PoiContextUtil.getContext().getRootObjectMap(),sheet);
	}

	public void writerRow(RowModelVO rowModelVO, Object dataObj, Sheet sheet) {
		LoopRowModelVO loopRow = (LoopRowModelVO) rowModelVO;
		List<BaseModel> cellList = loopRow.getCellList();
		// 记录当前行
		Row writerRow = null;// sheet.createRow(PoiContextUtil.getContext().getWriterRowNum());
		// int currentRowNum=writerRow.getRowNum();
		Integer cellCurrentRowNum = null;
		List<Object> dataList = null;
		if (dataObj instanceof HashMap) {
			dataList = RegexUtils.resolveList("${"+loopRow.getKeyeExpression()+"}");
		} else {
			dataList = RegexUtils.parseValueList("#{"+loopRow.getKeyeExpression()+"}", dataObj);
		}
		for (Object obj : dataList) {
			for (int i = 0, l = cellList.size(); i < l; i++) {
				BaseModel baseModel = cellList.get(i);
				if (baseModel instanceof CellModelVO) {
					CellModelVO cellVO = (CellModelVO) baseModel;
					if (null != cellVO.getCell()) {
						if (null == cellCurrentRowNum || cellCurrentRowNum.intValue() != cellVO.getCell().getRowIndex()) {
							writerRow = sheet.createRow(PoiContextUtil.getContext().getWriterRowNum());
							cellCurrentRowNum = cellVO.getCell().getRowIndex();
							//复制样式(行)
							//ExcelOperationUtil.copyRow(cellVO.getCell().getRow(),writerRow);
							//ExcelOneSheetUtil.copyMergeRegion(cellVO.getCell().getRow().getSheet(),cellVO.getCell().getRow().getRowNum(), PoiContextUtil.getContext().getWriterRowNum());
							// 更新写入行数
							PoiContextUtil.getContext().setWriterRowNum(PoiContextUtil.getContext().getWriterRowNum() + 1);
						}
						Cell createCell = writerRow.createCell(cellVO.getCell().getColumnIndex());
						//复制样式（单元格）
						ExcelOperationUtil.copyCell(cellVO.getCell(),createCell);
						String expression = cellVO.getExpression();
						if(null!=expression) {
							// log.info("解析rowIndex={},columnIndex={}", cell.getRowIndex(),
							// cell.getColumnIndex());
							log.info("expression={},obj={}",expression,obj);
							String resolvedContent = RegexUtils.parseValue(expression,obj);
							createCell.setCellValue(resolvedContent);
						}
						//记录是否需要合并单元格
						ExcelOneSheetUtil.isNeedMergen(cellVO.getCell(),createCell);
					}
					
				} else if (baseModel instanceof LoopRowModelVO) {// 循环节点
					LoopRowModelVO nextRowModel = (LoopRowModelVO) baseModel;
					writerRow(nextRowModel, obj,sheet);
				}
			}
		}
	}

	@Override
	public int support(RowModelVO row) {
		return 1;
	}

	public static void main(String[] args) {
		String content = "<poi:foreach list=\"list\"> #{index}";
//		String content = "<poi:foreach list=\"list\">";
		boolean flag = content.matches("<poi:foreach\\s+list=\"(\\w+)\">");
		System.out.println(flag);

		Pattern prePattern = Pattern.compile(CoreConstants.POI_FOREACH_START_REGEX);
		Matcher matcher = prePattern.matcher(content);
		boolean f = matcher.find();
		System.out.println(f);
		System.out.println(matcher.replaceAll(""));
	}

}
